package com.test.helloworld.controller;

import com.test.common.AbstractHttpFilter;
import com.test.helloworld.bean.Product;
import com.test.helloworld.dao.DaoFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/9/6 22:13
 */
//@WebFilter(filterName = "filterDispatcher", urlPatterns = "*.action")
public class FilterDispatcher extends AbstractHttpFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(FilterDispatcher.class);
    private static final String LIST_PATH = "/product-input.action";
    private static final String SAVE_PATH = "/product-save.action";

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //1.获取servletPath
        String servletPath = request.getServletPath();
        String servletPathLast = servletPath.substring(servletPath.lastIndexOf("/"));
        LOGGER.info(servletPath);
        String path = null;

        //2.判断servletPath，若其等于/product-input.action，则转发到/WEB-INF/app1/input.jsp
        if (LIST_PATH.equals(servletPathLast)) {
            path = "/WEB-INF/app1/input.jsp";
        }

        //3.若其等于/product-save.action，则
        if (SAVE_PATH.equals(servletPathLast)) {
            //3.1) 获取请求参数
            String productName = request.getParameter("productName");
            String productDesc = request.getParameter("productDesc");
            double productPrice = Double.parseDouble(request.getParameter("productPrice"));
            //3.2）把请求信息封装成product对象
            Product product = new Product(productName, productDesc, productPrice);
            //3.3）执行保存操作
            Long id = DaoFactory.getProductDao().saveProduct(product);
            product.setId(id);
            //3.4) 把Product对象保存到request中，${param.productName --> ${requestScope.product.productName}}
            request.setAttribute("product", product);
            path = "/WEB-INF/app1/details.jsp";
        }

        if (path != null) {
            request.getRequestDispatcher(path).forward(request, response);
            return;
        }

        chain.doFilter(request, response);
    }

    @Override
    protected void init() {

    }
}
